package boddaert.philippe.cashGame.site.splitgames;

import java.io.IOException;
import java.util.List;

import boddaert.philippe.cashGame.net.DefaultWebPageGetterFactory;
import boddaert.philippe.cashGame.net.Net;
import boddaert.philippe.cashGame.net.WebPageGetter;
import boddaert.philippe.cashGame.net.WebPageGetterFactory;
import boddaert.philippe.cashGame.parser.page.WebPageParserFactory;
import boddaert.philippe.cashGame.site.ParsedSite;
import boddaert.philippe.cashGame.site.Site;
import boddaert.philippe.cashGame.site.SiteRubrique;
import boddaert.philippe.cashGame.site.WebPage;

import au.id.jericho.lib.html.Element;
import au.id.jericho.lib.html.Source;

public class WebSiteGetter {

	private static Site siteDefinition = new SplitGames();

	public static int getNumberOfPageToLoad(String urlSite) throws IOException {
		WebPage webPage = DefaultWebPageGetterFactory.get().get(urlSite);
		return parseNumberOfPage(webPage.getContent());
	}

	private static int parseNumberOfPage(String content) {
		Source source = new Source(content);
		List<Element> findAllElements = source.findAllElements("li");
		for (Element element : findAllElements) {
			if ("in-end".equals(element.getAttributeValue("class"))) {
				Element link = (Element) element.getChildElements().get(0);
				String[] split = link.getAttributeValue("href").split("/");
				return Integer
						.parseInt(split[split.length - 1].split("\\.")[0]);
			}
		}
		return -1;
	}

	public static ParsedSite getSite() throws Exception {
		List<SiteRubrique> rubrique = siteDefinition.getRubriques();
		ParsedSite site = new ParsedSite();
		site.setName("splitGames");
		int numberOfPageRubrique = 0;
		for (SiteRubrique siteRubrique : rubrique) {

			String url = siteDefinition.getUrl(siteRubrique.getId());
			numberOfPageRubrique = getNumberOfPageToLoad(url);
			for (int i = 1; i <= numberOfPageRubrique; i++) {
				site.addPage(WebPageParserFactory.get(
						boddaert.philippe.cashGame.Site.SPLITGAMES)
						.parse(
								DefaultWebPageGetterFactory.get().get(
										siteDefinition.getUrl(siteRubrique
												.getId(), i))));
			}
		}
		return site;
	}

}
